package jp.ac.u_tokyo.dch.dao.common;

import org.apache.commons.lang.xwork.StringUtils;

import jp.ac.u_tokyo.dch.core.db.CustomPreparedStatement;
import jp.ac.u_tokyo.dch.core.db.CustomResultSet;
import jp.ac.u_tokyo.dch.core.db.DBConnection;
import jp.ac.u_tokyo.dch.core.exceptions.DBException;
import jp.ac.u_tokyo.dch.model.db.FieldMaster;
import jp.ac.u_tokyo.dch.util.common.CommonDBConnection;

public class PsiDao {


	/**
	 * DBコネクションオブジェクト
	 */
	private DBConnection dbconn = null;

	/**
	 * 生成者
	 *
	 * @param DBコネクションオブジェクト
	 */
	public PsiDao(DBConnection dbconn) {
		this.dbconn = dbconn;
	}

	public int insert(String psiid, String psiname) throws DBException {

		if (!StringUtils.isEmpty(selectPsiName(psiid))) {

			return 0;
		}

		CustomPreparedStatement ps = null;
		int result = 0;
		try{
			String query = "INSERT INTO psi_table (psiid,psidisplayname)  VALUES (?,?)";
			ps = dbconn.prepareStatement(query);

			int index = 1;
			ps.setString(index++, psiid);
			ps.setString(index++, psiname);

			result = ps.executeUpdate();
		}catch(DBException dbe){
			throw dbe;
		}finally{
			if(ps != null) ps.close();
		}

		return result;
	}

	public int update(String psiid, String psiname) throws DBException {

		if (!StringUtils.isEmpty(selectPsiName(psiid))) {

			return 0;
		}

		CustomPreparedStatement ps = null;
		int result = 0;
		try{
			String query = "UPDATE psi_table SET psidisplayname = ? WHERE psiid = ? ";
			ps = dbconn.prepareStatement(query);

			int index = 1;
			ps.setString(index++, psiname);
			ps.setString(index++, psiid);

			result = ps.executeUpdate();
		}catch(DBException dbe){
			throw dbe;
		}finally{
			if(ps != null) ps.close();
		}

		return result;
	}

	public String selectPsiName(String psiid) throws DBException {

		String query = "select * from psi_table where psiid = ?";

		String result = null;
		CustomPreparedStatement ps = null;
		CustomResultSet rs = null;
		try {
			ps = dbconn.prepareStatement(query);
			ps.setString(1, psiid);
			rs = ps.executeQuery();

			if (rs.next()) {

				result = rs.getString("psidisplayname");
			}

		} catch (DBException dbe) {
			throw dbe;
		} finally {
			CommonDBConnection.closeResource(ps, rs);
		}
		return result;
	}

}
